<template>
  <div class="space-report-container">
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>广告位小时报表查询</span>
        </div>
      </template>
      
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="广告位" required>
          <el-select v-model="searchForm.adspaceId" placeholder="请选择广告位" clearable filterable>
            <el-option
              v-for="space in spaceOptions"
              :key="space.id"
              :label="space.name"
              :value="space.id"
            />
          </el-select>
        </el-form-item>
        

        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <el-card class="box-card">
      <div class="chart-container">
        <div ref="chartRef" style="width: 100%; height: 400px;"></div>
      </div>
      
      <div class="data-info">
        <el-descriptions title="数据统计" :column="3" border>
          <el-descriptions-item label="数据总数">{{ chartData.length }}</el-descriptions-item>
          <el-descriptions-item label="请求总数">{{ totalRequests }}</el-descriptions-item>
          <el-descriptions-item label="填充总数">{{ totalForwards }}</el-descriptions-item>
          <el-descriptions-item label="获胜总数">{{ totalWins }}</el-descriptions-item>
          <el-descriptions-item label="展示总数">{{ totalImps }}</el-descriptions-item>
          <el-descriptions-item label="点击总数">{{ totalClicks }}</el-descriptions-item>
          <el-descriptions-item label="最大请求数">{{ maxRequests }}</el-descriptions-item>
          <el-descriptions-item label="最大填充数">{{ maxForwards }}</el-descriptions-item>
          <el-descriptions-item label="最大获胜数">{{ maxWins }}</el-descriptions-item>
          <el-descriptions-item label="最大展示数">{{ maxImps }}</el-descriptions-item>
          <el-descriptions-item label="最大点击数">{{ maxClicks }}</el-descriptions-item>
          <el-descriptions-item label="平均请求数">{{ formatNumber(avgRequests) }}</el-descriptions-item>
          <el-descriptions-item label="平均填充数">{{ formatNumber(avgForwards) }}</el-descriptions-item>
          <el-descriptions-item label="平均获胜数">{{ formatNumber(avgWins) }}</el-descriptions-item>
          <el-descriptions-item label="平均展示数">{{ formatNumber(avgImps) }}</el-descriptions-item>
          <el-descriptions-item label="平均点击数">{{ formatNumber(avgClicks) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import * as echarts from 'echarts'
import type { ECharts, EChartsOption } from 'echarts'
import { fetchSpaceHourReportData, type ApiHourReportItem } from '@/api/report'
import { fetchSpaceData, type ApiSpaceItem } from '@/api/space'
import { Search, Refresh } from '@element-plus/icons-vue'

// 路由实例
const route = useRoute()
const router = useRouter()

// 图表实例引用
const chartRef = ref<HTMLDivElement>()
let chartInstance: ECharts | null = null

// 搜索表单
interface SearchForm {
  adspaceId: string
}

const searchForm = reactive<SearchForm>({
  adspaceId: ''
})

// 广告位选项
interface SpaceOption {
  id: string
  name: string
}

const spaceOptions = ref<SpaceOption[]>([])
const loading = ref(false)

// 真实数据 - 多指标
interface ChartDataItem {
  name: string
  requests: number
  forwards: number
  wins: number
  imps: number
  clicks: number
}

const chartData = ref<ChartDataItem[]>([])

// 指标选项
const metrics = [
  { key: 'requests', name: '请求数', color: '#5470c6' },
  { key: 'forwards', name: '填充数', color: '#ee6666' },
  { key: 'wins', name: '获胜数', color: '#73c0de' },
  { key: 'imps', name: '展示数', color: '#91cc75' },
  { key: 'clicks', name: '点击数', color: '#fac858' }
]

// 加载广告位选项数据
const loadSpaceOptions = async () => {
  try {
    const params = {
      current: 1,
      size: 1000 // 获取所有广告位数据
    }
    
    const response = await fetchSpaceData(params)
    spaceOptions.value = response.records.map(item => ({
      id: item.id || '',
      name: item.name || ''
    }))
  } catch (error) {
    console.error('加载广告位选项失败:', error)
  }
}

// 加载真实数据
const loadRealData = async () => {
  if (!searchForm.adspaceId) {
    chartData.value = []
    return
  }
  
  loading.value = true
  try {
    const params = {
      // 当前日期，格式为YYYYMMDD
      dt: new Date().toISOString().slice(0, 10).replace(/-/g, ''),
      adspaceId: searchForm.adspaceId
    }
    
    const response = await fetchSpaceHourReportData(params)
    
    // 转换数据格式：小时为x轴，包含多个指标
    chartData.value = response.map(item => ({
      name: item.hour || '',
      requests: item.requests || 0,
      forwards: item.forwards || 0,
      wins: item.wins || 0,
      imps: item.imps || 0,
      clicks: item.clicks || 0
    }))
    
    // 更新图表
    updateChart()
  } catch (error) {
    console.error('加载广告位时报表数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return
  
  const option: EChartsOption = {
    xAxis: {
      data: chartData.value.map(item => item.name)
    },
    series: metrics.map(metric => ({
      name: metric.name,
      type: 'bar',
      data: chartData.value.map(item => item[metric.key as keyof ChartDataItem] as number),
      itemStyle: {
        color: metric.color
      }
    }))
  }
  chartInstance.setOption(option)
}

// 搜索处理
const handleSearch = () => {
  updateUrlParams()
  loadRealData()
}

// 重置搜索表单
const handleReset = () => {
  searchForm.adspaceId = ''
  chartData.value = []
  
  // 更新URL参数
  router.replace({ query: { ...route.query, adspaceId: undefined } })
  
  if (chartInstance) {
    const option: EChartsOption = {
      xAxis: {
        data: []
      },
      series: [
        {
          data: []
        }
      ]
    }
    chartInstance.setOption(option)
  }
}

// 解析URL参数并设置搜索表单
const parseUrlParams = () => {
  const adspaceId = route.query.adspaceId as string
  if (adspaceId) {
    searchForm.adspaceId = adspaceId
    return true
  }
  return false
}

// 更新URL参数
const updateUrlParams = () => {
  if (searchForm.adspaceId) {
    router.replace({ query: { ...route.query, adspaceId: searchForm.adspaceId } })
  } else {
    router.replace({ query: { ...route.query, adspaceId: undefined } })
  }
}

// 计算属性
const totalRequests = computed(() => {
  return chartData.value.reduce((sum, item) => sum + item.requests, 0)
})

const totalForwards = computed(() => {
  return chartData.value.reduce((sum, item) => sum + item.forwards, 0)
})

const totalWins = computed(() => {
  return chartData.value.reduce((sum, item) => sum + item.wins, 0)
})

const totalImps = computed(() => {
  return chartData.value.reduce((sum, item) => sum + item.imps, 0)
})

const totalClicks = computed(() => {
  return chartData.value.reduce((sum, item) => sum + item.clicks, 0)
})

const maxRequests = computed(() => {
  return chartData.value.length > 0 ? Math.max(...chartData.value.map(item => item.requests)) : 0
})

const maxForwards = computed(() => {
  return chartData.value.length > 0 ? Math.max(...chartData.value.map(item => item.forwards)) : 0
})

const maxWins = computed(() => {
  return chartData.value.length > 0 ? Math.max(...chartData.value.map(item => item.wins)) : 0
})

const maxImps = computed(() => {
  return chartData.value.length > 0 ? Math.max(...chartData.value.map(item => item.imps)) : 0
})

const maxClicks = computed(() => {
  return chartData.value.length > 0 ? Math.max(...chartData.value.map(item => item.clicks)) : 0
})

const avgRequests = computed(() => {
  return chartData.value.length > 0 ? totalRequests.value / chartData.value.length : 0
})

const avgForwards = computed(() => {
  return chartData.value.length > 0 ? totalForwards.value / chartData.value.length : 0
})

const avgWins = computed(() => {
  return chartData.value.length > 0 ? totalWins.value / chartData.value.length : 0
})

const avgImps = computed(() => {
  return chartData.value.length > 0 ? totalImps.value / chartData.value.length : 0
})

const avgClicks = computed(() => {
  return chartData.value.length > 0 ? totalClicks.value / chartData.value.length : 0
})

// 格式化数字显示
const formatNumber = (num: number) => {
  if (num === 0 || isNaN(num)) return '0'
  return num.toFixed(0)
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance = echarts.init(chartRef.value)
  
  const option: EChartsOption = {
    title: {
      text: '广告位多指标统计',
      left: 'center',
      textStyle: {
        fontSize: 18,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params: any) => {
        const item = chartData.value[params[0].dataIndex]
        let result = `${params[0].name}<br/>`
        params.forEach((param: any) => {
          result += `${param.seriesName}: ${param.value}<br/>`
        })
        return result
      }
    },
    legend: {
      data: metrics.map(metric => metric.name),
      top: 'bottom'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.map(item => item.name),
      axisLabel: {
        rotate: 45
      },
      name: '日期'
    },
    yAxis: {
      type: 'value',
      name: '数量',
      nameTextStyle: {
        padding: [0, 0, 0, -30]
      }
    },
    series: metrics.map(metric => ({
      name: metric.name,
      type: 'bar',
      data: chartData.value.map(item => item[metric.key as keyof ChartDataItem] as number),
      itemStyle: {
        color: metric.color
      },
      emphasis: {
        itemStyle: {
          color: metric.color
        }
      }
    }))
  }
  
  chartInstance.setOption(option)
}

// 刷新数据
const refreshData = () => {
  if (searchForm.adspaceId) {
    loadRealData()
  }
}

// 响应窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

onMounted(async () => {
  // 加载广告位选项数据
  await loadSpaceOptions()
  
  // 初始化图表
  initChart()
  
  // 解析URL参数
  const hasUrlParams = parseUrlParams()
  
  // 如果URL中有adspaceId参数，自动查询
  if (hasUrlParams && searchForm.adspaceId) {
    await loadRealData()
  }
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 清理图表实例
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
/* 动画定义 */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(-30px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(102, 126, 234, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(102, 126, 234, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(102, 126, 234, 0);
  }
}

@keyframes shimmer {
  0% {
    background-position: -200px 0;
  }
  100% {
    background-position: calc(200px + 100%) 0;
  }
}

.space-report-container {
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 40px);
  animation: fadeInUp 0.8s ease-out;
}

.search-card {
  margin-bottom: 24px;
  max-width: 1200px;
  margin: 0 auto 24px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  animation: slideInUp 0.6s ease-out;
}

.box-card {
  margin: 0 auto;
  max-width: 1200px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  animation: slideInUp 0.8s ease-out;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #2c3e50;
}

.chart-container {
  margin: 24px 0;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 16px;
  padding: 24px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  animation: slideInUp 1s ease-out;
}

.data-info {
  margin-top: 24px;
  animation: slideInRight 0.8s ease-out;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: 600;
  color: #2c3e50;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #667eea;
}

:deep(.el-descriptions__content) {
  color: #2c3e50;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 8px;
  transition: all 0.3s ease;
  font-weight: 500;
  margin-left: 8px;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.4);
  animation: pulse 1.5s infinite;
}

:deep(.el-button--default:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

/* 表单元素样式 */
:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #2c3e50;
}

:deep(.el-input__inner) {
  border-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

:deep(.el-input__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
  transform: translateY(-1px);
  background: rgba(255, 255, 255, 0.95);
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-select__wrapper) {
  border-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

:deep(.el-select__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

:deep(.el-date-editor) {
  border-radius: 8px;
  border: 1px solid rgba(102, 126, 234, 0.2);
  background: rgba(255, 255, 255, 0.8);
  transition: all 0.3s ease;
}

:deep(.el-date-editor:hover) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

/* 图表样式 */
:deep(.echarts) {
  border-radius: 12px;
  overflow: hidden;
}

/* 表格圆角 */
:deep(.el-table) {
  border-radius: 12px;
  overflow: hidden;
}

/* 表头样式 */
:deep(.el-table__header-wrapper) {
  border-radius: 12px 12px 0 0;
  overflow: hidden;
}

:deep(.el-table__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.el-table th) {
  background: transparent;
  color: #ffffff;
  font-weight: 600;
}

:deep(.el-table th.el-table__cell) {
  background: transparent;
}

/* 卡片标题样式 */
.card-header {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: center;
  margin-top: 24px;
}

:deep(.el-pagination__total),
:deep(.el-pagination__sizes),
:deep(.el-pagination__jump) {
  color: #2c3e50;
  font-weight: 500;
}

/* 加载动画 */
:deep(.el-loading-mask) {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
}

:deep(.el-loading-spinner .circular) {
  animation: rotate 2s linear infinite;
}

:deep(.el-loading-spinner .path) {
  stroke: #667eea;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .space-report-container {
    padding: 16px;
  }
  
  .search-card,
  .box-card {
    margin-left: 16px;
    margin-right: 16px;
  }
  
  .chart-container {
    margin: 16px 0;
    padding: 16px;
  }
}

@media (max-width: 768px) {
  .space-report-container {
    padding: 12px;
  }
  
  .search-card,
  .box-card {
    margin-left: 12px;
    margin-right: 12px;
  }
  
  .chart-container {
    margin: 12px 0;
    padding: 12px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
  
  :deep(.el-form--inline .el-form-item) {
    display: block;
    margin-right: 0;
    margin-bottom: 12px;
  }
  
  :deep(.el-descriptions) {
    font-size: 12px;
  }
}
</style>